package com.henu.yizhiya;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.henu.R;
import com.henu.yizhiya.entity.Person;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class RegisterActivity extends AppCompatActivity {
    private EditText et_res_username,et_res_pwd,et_res_phone;
    private Button btn_res_create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //引入Bmob
        Bmob.initialize(this, "a24db0fac16b375a97072b85080ea20f");
        //获取视图对象
        et_res_username = (EditText) findViewById(R.id.et_res_username);
        et_res_pwd = (EditText) findViewById(R.id.et_res_pwd);
        et_res_phone = (EditText) findViewById(R.id.et_res_phone);
        btn_res_create = (Button) findViewById(R.id.btn_res_create);
        btn_res_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  register();
            }
        });
    }

    //注册
    public void register(){
        String name = et_res_username.getText().toString().trim();
        String pwd = et_res_pwd.getText().toString().trim();
        String number = et_res_phone.getText().toString().trim();
        if (name.equals("")) {
            Toast.makeText(RegisterActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();

        } else if (pwd.length()<6) {
            Toast.makeText(RegisterActivity.this,"密码少于6位",Toast.LENGTH_SHORT).show();
        }else if (number.length()!=11){
            Toast.makeText(RegisterActivity.this,"手机号不合法",Toast.LENGTH_SHORT).show();
        }else{
            BmobUser person = new BmobUser();
            person.setUsername(name);
            person.setPassword(pwd);
            person.setMobilePhoneNumber(number);
            person.signUp(new SaveListener<Person>() {
                @Override
                public void done(Person p, BmobException e) {
                    if(e==null){
                        Toast.makeText(RegisterActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }else{
                        Toast.makeText(RegisterActivity.this,"注册失败--"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
}
